// pages/mine/mine.js
const app = getApp();

Page({
  data: {
    // 登录相关
    isLoggedIn: false,
    isAdmin: false,
    userInfo: {
      avatarUrl: '/images/default-avatar.png',
      nickName: '未登录用户'
    },
    userBalance: 0,

    // 口味设置相关
    showAvoidModal: false,
    selectedAvoid: '没有忌口',
    simpleAvoidOptions: ['没有忌口', '不吃辣', '少辣', '不吃葱姜蒜', '不吃香菜', '不吃海鲜', '素食'],

    // 模态框相关
    showBalanceModal: false,
    showAddModal: false,
    userId: '',
    balanceAmount: '',
    errorMsg: '',
    
    // 添加菜品相关
    categories: ['家常小炒', '时令素菜', '蒸煮鲜食', '荤素炖菜', '凉拌小菜', '家常汤羹', '小酒饮料'],
    categoryIndex: 0,
    dishName: '',
    dishIngredients: '',
    preciousIngredients: '',

    // 其他数据
    cart: [],
    cartCount: 0
  },

  onLoad: function(options) {
    // 检查登录状态
    this.checkLoginStatus();
    
    // 加载其他数据
    const cart = wx.getStorageSync('cart') || [];
    const cartCount = cart.reduce((total, item) => total + item.quantity, 0);
    
    // 加载忌口设置
    const savedAvoid = wx.getStorageSync('selectedAvoid') || '没有忌口';
    
    this.setData({
      cart,
      cartCount,
      selectedAvoid: savedAvoid
    });
  },

  onShow: function() {
    // 每次显示页面时检查登录状态
    this.checkLoginStatus();
    
    // 加载其他数据
    const cart = wx.getStorageSync('cart') || [];
    const cartCount = cart.reduce((total, item) => total + item.quantity, 0);
    const savedAvoid = wx.getStorageSync('userAvoidPreferences') || '没有忌口';
    
    this.setData({ 
      cart, 
      cartCount,
      selectedAvoid: savedAvoid
    });
  },

  // 检查登录状态
  checkLoginStatus: function() {
    const token = wx.getStorageSync('token');
    const userInfo = wx.getStorageSync('userInfo');
    const userType = wx.getStorageSync('userType');
    
    console.log('检查登录状态:', { token, userInfo, userType });
    
    if (token && userInfo) {
      this.setData({
        isLoggedIn: true,
        userInfo: userInfo,
        isAdmin: userType === '主理人' || userType === '私厨'
      });
      
      // 更新全局状态
      if (app.globalData) {
        app.globalData.userInfo = userInfo;
        app.globalData.userType = userType;
        app.globalData.isAdmin = this.data.isAdmin;
      }
    } else {
      this.setData({
        isLoggedIn: false,
        isAdmin: false,
        userInfo: {
          avatarUrl: '/images/default-avatar.png',
          nickName: '未登录用户'
        }
      });
    }
  },

  // 跳转到登录页面
  goToLogin: function() {
    wx.navigateTo({
      url: '/pages/login/login'
    });
  },

  // 退出登录
  handleLogout: function() {
    wx.showModal({
      title: '确认退出',
      content: '您确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          // 清除本地存储
          wx.removeStorageSync('token');
          wx.removeStorageSync('userInfo');
          wx.removeStorageSync('userType');
          
          this.setData({
            isLoggedIn: false,
            isAdmin: false,
            userInfo: {
              avatarUrl: '/images/default-avatar.png',
              nickName: '未登录用户'
            }
          });
          
          // 清除全局状态
          if (app.globalData) {
            app.globalData.userInfo = null;
            app.globalData.userType = '';
            app.globalData.isAdmin = false;
          }
          
          wx.showToast({
            title: '已退出登录',
            icon: 'success'
          });
        }
      }
    });
  },

  // 口味设置函数
  tasteDetail: function() {
    this.setData({
      showAvoidModal: true
    });
  },

  selectSimpleAvoid: function(e) {
    const item = e.currentTarget.dataset.item;
    this.setData({
      selectedAvoid: item
    });
  },

  confirmAvoidSelection: function() {
    wx.setStorageSync('userAvoidPreferences', this.data.selectedAvoid);
    this.setData({
      showAvoidModal: false
    });
    
    wx.showToast({
      title: '口味设置已保存',
      icon: 'success',
      duration: 1500
    });
  },

  hideAvoidModal: function() {
    this.setData({
      showAvoidModal: false
    });
  },

  // 页面跳转函数
  navigateToDishAdmin: function() {
    wx.navigateTo({
      url: '/pages/dish-admin/dish-admin'
    });
  },

  navigateToOrderAdmin: function() {
    wx.navigateTo({
      url: '/pages/order-admin/order-admin'
    });
  },

  navigateToMyOrders: function() {
    wx.navigateTo({
      url: '/pages/order/order'
    });
  },

  showBalanceDetail: function() {
    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    });
  },

  // 模态框函数
  showAddBalanceModal: function() {
    this.setData({
      showBalanceModal: true,
      userId: '',
      balanceAmount: '',
      errorMsg: ''
    });
  },

  hideBalanceModal: function() {
    this.setData({
      showBalanceModal: false
    });
  },

  onUserIdInput: function(e) {
    this.setData({
      userId: e.detail.value
    });
  },

  onBalanceAmountInput: function(e) {
    this.setData({
      balanceAmount: e.detail.value
    });
  },

  addUserBalance: function() {
    const { userId, balanceAmount } = this.data;
    
    if (!userId) {
      this.setData({ errorMsg: '请输入用户ID' });
      return;
    }
    
    if (!balanceAmount || balanceAmount < 1 || balanceAmount > 1000) {
      this.setData({ errorMsg: '请输入1-1000之间的数量' });
      return;
    }
    
    wx.showToast({
      title: '添加成功',
      icon: 'success'
    });
    
    this.hideBalanceModal();
  },

  showAddDishModal: function() {
    this.setData({
      showAddModal: true,
      dishName: '',
      dishIngredients: '',
      preciousIngredients: '',
      categoryIndex: 0
    });
  },

  hideAddDishModal: function() {
    this.setData({
      showAddModal: false
    });
  },

  onCategoryChange: function(e) {
    this.setData({
      categoryIndex: parseInt(e.detail.value)
    });
  },

  onDishNameInput: function(e) {
    this.setData({
      dishName: e.detail.value
    });
  },

  onIngredientsInput: function(e) {
    this.setData({
      dishIngredients: e.detail.value
    });
  },

  onPreciousInput: function(e) {
    this.setData({
      preciousIngredients: e.detail.value
    });
  },

  addDish: function() {
    const { dishName, dishIngredients, categoryIndex, categories } = this.data;
    
    if (!dishName) {
      wx.showToast({
        title: '请输入菜品名称',
        icon: 'none'
      });
      return;
    }
    
    if (!dishIngredients) {
      wx.showToast({
        title: '请输入主要材料',
        icon: 'none'
      });
      return;
    }
    
    const newDish = {
      id: 'custom_' + new Date().getTime(),
      name: dishName,
      ingredients: dishIngredients,
      category: categories[categoryIndex],
      imgUrl: '/images/default-dish.jpg'
    };
    
    const customDishes = wx.getStorageSync('customDishes') || [];
    customDishes.push(newDish);
    wx.setStorageSync('customDishes', customDishes);
    
    wx.showToast({
      title: '添加成功',
      icon: 'success'
    });
    
    this.hideAddDishModal();
  }
});